package com.zhentao.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.payment.entity.PaymentOrder;
import com.zhentao.payment.entity.RefundOrder;
import com.zhentao.payment.mapper.PaymentOrderMapper;
import com.zhentao.payment.mapper.RefundOrderMapper;
import com.zhentao.payment.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 统计服务实现类
 */
@Service
public class StatisticsServiceImpl implements StatisticsService {
    
    @Autowired
    private PaymentOrderMapper paymentOrderMapper;
    
    @Autowired
    private RefundOrderMapper refundOrderMapper;
    
    @Override
    public Map<String, Object> getTodayStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取今天的开始时间
        LocalDateTime today = LocalDateTime.now().with(LocalTime.MIN);
        
        // 统计今日支付总额和笔数
        LambdaQueryWrapper<PaymentOrder> paymentWrapper = new LambdaQueryWrapper<>();
        paymentWrapper.ge(PaymentOrder::getCreateTime, today)
                     .eq(PaymentOrder::getStatus, 1); // 已支付状态
        
        result.put("paymentCount", paymentOrderMapper.selectCount(paymentWrapper));
        
        // 计算支付总额
        BigDecimal paymentAmount = paymentOrderMapper.selectList(paymentWrapper)
                .stream()
                .map(PaymentOrder::getAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        result.put("paymentAmount", paymentAmount);
        
        // 统计今日退款总额和笔数
        LambdaQueryWrapper<RefundOrder> refundWrapper = new LambdaQueryWrapper<>();
        refundWrapper.ge(RefundOrder::getCreateTime, today)
                    .eq(RefundOrder::getStatus, 1); // 已退款状态
        
        result.put("refundCount", refundOrderMapper.selectCount(refundWrapper));
        
        // 计算退款总额
        Double refundAmount = refundOrderMapper.selectList(refundWrapper)
                .stream()
                .mapToDouble(RefundOrder::getAmount)
                .sum();
        result.put("refundAmount", refundAmount);
        
        return result;
    }
} 